package jobs.job3.classloaderdemo.server.loader;

import jobs.job3.classloaderdemo.server.standard.bean.TaskBean;
import jobs.job3.classloaderdemo.server.standard.Task;

import java.io.*;
import java.lang.reflect.InvocationTargetException;

public class NetworkTaskLoader extends ClassLoader {
    InputStream in;

    public NetworkTaskLoader(InputStream in) {
        this.in = in;
    }

    public ExecutableTask receiveTask() throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        DataInputStream din = new DataInputStream(in);
        int len = din.readInt();
        byte[] bytes = new byte[len];
        din.readFully(bytes);
        System.out.println("收到《计算任务》数据包大小共：" + (bytes.length + 4) + " 个字节");
        TaskBean taskBean = TaskBean.deserialize(bytes);

        byte[] algorithm = taskBean.getTaskBytes();
        String className = taskBean.getClassName();
        byte[] input = taskBean.getInput();


        Class<?> taskClass = defineClass(className, algorithm, 0, algorithm.length);
        Object taskObj = taskClass.getConstructor().newInstance();
        System.out.println("《计算任务》@" + className + " 成功实例化");
        //noinspection rawtypes
        Task<?,?> task = (Task) taskObj;

        return new ExecutableTask(task, input);
    }
}
/*
0 1~9       9      0~8    nextInt(9)
1 2~9       8      0~7    nextInt(8)
2 3~9       7      0~6    nextInt(7)    i+1
...

 */




